package com.xfb.jdbc.sqlSession;

import com.xfb.jdbc.config.BoundSql;
import com.xfb.jdbc.pojo.Configuration;
import com.xfb.jdbc.pojo.MappedStatement;
import com.xfb.jdbc.utils.GenericTokenParser;
import com.xfb.jdbc.utils.ParameterMapping;
import com.xfb.jdbc.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: Xing Fang Bin
 * @Date: 2021/07/01/15:08
 * @Description:
 */
public class SimpleExecutor implements Executor {

    public PreparedStatement setConfig(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        //1、注册驱动
        Connection connection = configuration.getDataSource().getConnection();

        //2、获取sql语句：select * from user where id=#{id} and username=#{username}  需要替换占位符
        //替换为select * from user where id=？ and username=？ 才能被jdbc识别
        String sql = mappedStatement.getSql();

        BoundSql boundSql = getBoundSql(sql);

        //3、获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //4、设置参数
        //根据全路径获取class对象
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Object o;
            if (parameterType.equals("java.lang.Integer")||
                    parameterType.equals("java.lang.Byte")||
                    parameterType.equals("java.lang.Double")||
                    parameterType.equals("java.lang.Long")||
                    parameterType.equals("java.lang.Short")||
                    parameterType.equals("java.lang.Character")||
                    parameterType.equals("java.lang.Boolean")||
                    parameterType.equals("java.lang.Float")) {
                o = params[0];
            } else {
                //利用反射获取对象
                Field declaredField = parameterTypeClass.getDeclaredField(content);
                //暴力访问
                 declaredField.setAccessible(true);
                o = declaredField.get(params[0]);
            }
            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = setConfig(configuration, mappedStatement, params);

        //5、执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultClassType = getClassType(resultType);
        ArrayList<Object> list = new ArrayList<>();

        //6、封装返回结果集
        while (resultSet.next()) {
            //创建对象
            Object newInstance = resultClassType.newInstance();
            //去除resultSet的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //获取字段名
                String columnName = metaData.getColumnName(i);
                //获取字段值
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClassType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(newInstance, value);
            }
            list.add(newInstance);
        }

        return (List<E>) list;
    }

    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = setConfig(configuration, mappedStatement, params);
        //5、执行sql
        int resultSet = 0;
        try {
            resultSet = preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return resultSet;
        }
        return resultSet;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            Class<?> forName = Class.forName(parameterType);
            return forName;
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作：1、将#{}使用？作为代替  2、解析出#{}里的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类：配合标记解析器完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析处理的sql
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
